package com.kklsqm.langchain4j.service.impl;

import com.kklsqm.langchain4j.assistant.DeepSeekAssistant;
import com.kklsqm.langchain4j.assistant.QwenAssistant;
import com.kklsqm.langchain4j.service.ILangChainTTSService;
import dev.langchain4j.service.TokenStream;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

/**
 * 功能: 语音合成服务
 * 作者: 沙琪马
 * 日期: 2025/4/23 11:11
 */
@Service
@Slf4j
public class LangChainTTSServiceImpl implements ILangChainTTSService {

    @Resource
    private QwenAssistant qwenAssistant;

    // 生成朋友圈，小红书，快手口播，抖音口播的文案
    public String refineText(String text,String extraInfo) {
        return qwenAssistant.extraInfoChat(text, extraInfo);
    }

    /**
     * 流式聊天（Flux格式）
     *
     * @param assistant AI助手实例
     * @param sessionId 会话ID
     * @param role 角色定义
     * @param question 问题内容
     * @param extraInfo 额外信息
     * @return Flux<String>流
     */
    public Flux<String> chatStreamFlux(DeepSeekAssistant assistant, String sessionId, String role, String question, String extraInfo, String modelName) {


        TokenStream tokenStream = assistant.chatStreamTokenStream(sessionId, role, question, extraInfo);
        Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();

        tokenStream.onPartialResponse(partialResponse -> sink.tryEmitNext(partialResponse));
        tokenStream.onError(sink::tryEmitError);
        tokenStream.onCompleteResponse(rsp -> {
            sink.tryEmitComplete();
//            if (modelName != null) {
//                BigDecimal useToken = TokenTool.calculateTotalTokenConsumption(modelName, rsp.tokenUsage());
//                aiTokenService.calculateCost(useToken.longValue(), SymbolEnum.REDUCE, AiActionEnum.CHAT);
//                log.info("sessionId:{},消耗token数量:{}", sessionId, useToken);

//            }
        });
        tokenStream.start();
        return sink.asFlux();



    }
}
